package com.yidian.controller.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yidian.controller.utils.WebUtil;
import com.yidian.pojo.system.LoginLog;
import com.yidian.server.system.LoginLogService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author whb
 * @create 2021-06-09 15:21
 * @desciption 登录成功处理器（SpringSecurity安全框架）
 */
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Reference
    private LoginLogService loginLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("系统管理登录成功，被登录成功处理器拦截..");

        //获取登录用户
        String loginName = authentication.getName();
        //获取客户机的ip地址
        String ip = request.getRemoteAddr();
        //获取ip所在地区
        String cityByIP = WebUtil.getCityByIP(ip);
        //获取浏览器信息
        String browserInfo = request.getHeader("user-agent");
        browserInfo = WebUtil.getBrowserName(browserInfo);
        //获取登录时间
        Date loginTime = new Date();

        LoginLog loginLog = new LoginLog();
        loginLog.setLoginName(loginName);
        loginLog.setIp(ip);
        loginLog.setBrowserName(browserInfo);
        loginLog.setLocation(cityByIP);
        loginLog.setLoginTime(loginTime);

        //保存登录日志
        loginLogService.add(loginLog);

        request.getRequestDispatcher("/main.html").forward(request, response);
    }
}
